package com.backend.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.collections4.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Jackson:将List<Long>转化为List<String>,以防止前后端交互丢失精度
 *
 */
public class LongList2StringListSerializer extends JsonSerializer<List<Long>> {

  @Override
  public void serialize(List<Long> value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException {
    // 1.不为空则做转换处理
    if (CollectionUtils.isNotEmpty(value)) {
      List<String> strList = new ArrayList<>(value.size());
      for (Long aLong : value) {
        strList.add(String.valueOf(aLong));
      }
      // 格式化是否为空
      if (CollectionUtils.isNotEmpty(strList)) {
        gen.writeObject(strList);
        return;
      }
    }
    // 2.为空返回空集合
    gen.writeObject(Collections.EMPTY_LIST);
  }

}

